/**
 * author: lms
 */

const ElementHelper = {

  /**
   * 获取目标元素
   * @param element
   * @returns {Element | HTMLElement}
   */
  query(element) {
    if (typeof element === 'string') {
      element = document.querySelector(element);
    }
    element = element || document.body;
    return element
  },

  /**
   * 隐藏所有子元素
   */
  hideChildren(parentElement) {
    for (const element of parentElement.children) {
      this.hide(element)
    }
  },
  /**
   * 展示所有子元素
   */
  showChildren(parentElement) {
    for (const element of parentElement.children) {
      this.show(element)
    }
  },
  /**
   * 隐藏所有子元素
   */
  hide(element) {
    element.style.display = 'none'
  },
  /**
   * 展示所有子元素
   */
  show(element) {
    element.style.display = 'block'
  },
  remove(element) {
    element.remove()
  },
  /**
   * 将当前模板挂载到指定元素中
   */
  mount(that, element) {
    let tempDiv = document.createElement('div')
    element.appendChild(tempDiv)
    that.$mount(tempDiv)
  },
  /**
   * 将newEl元素追加到同父元素tarEl之后
   * @param newEl
   * @param tarEl
   */
  insertBefore(newEl, tarEl) {
    if(!tarEl) {
      console.log('找不到tarEl', tarEl)
      return
    }
    tarEl.parentElement.insertBefore(newEl, tarEl)
  },
  insertAfter(newEl, tarEl) {
    if(!tarEl) {
      console.warn('找不到tarEl', tarEl)
      return
    }
    tarEl.parentElement.insertBefore(newEl, tarEl)
    tarEl.parentElement.insertBefore(tarEl, newEl)
  },
  visible(element) {
    element.style.visibility = 'visible'
  },
  hidden(element) {
    element.style.visibility = 'hidden'
  },
  prepend(element) {
    element.parentElement.prepend(element)
  },
  /**
   * 监听元素变化
   * @param element
   * @param handler
   * @returns {HTMLIFrameElement}
   */
  observe(element, handler) {
    const config = { attributes: true, childList: false, subtree: false };
    const observer = new MutationObserver(handler);
    observer.observe(element, config);
  }
}

export default ElementHelper
